package cn.glutnn.service.impl;

import cn.glutnn.entity.Business;
import cn.glutnn.entity.Orders;
import cn.glutnn.mapper.FoodReviewsMapper;
import cn.glutnn.service.BusinessService;
import cn.glutnn.service.FoodReviewsService;
import cn.glutnn.service.OrdersService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.glutnn.entity.FoodReviews;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * (FoodReviews)表服务实现类
 *
 * @author msh
 * @since 2024-12-14 17:00:37
 */
@Service("foodReviewsService")
public class FoodReviewsServiceImpl extends ServiceImpl<FoodReviewsMapper, FoodReviews> implements FoodReviewsService {
    @Resource
    private BusinessService businessService;
    @Resource
    private OrdersService orderService;

    @Transactional
    public void rate(FoodReviews foodReviews) {
        // 检查订单是否存在且属于当前用户
        Orders order = orderService.getById(foodReviews.getOrderId());
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getUserId().equals(foodReviews.getUserId())) {
            throw new RuntimeException("无权评价此订单");
        }

        // 检查订单状态是否已完成
        if (order.getOrderState() != 2) {
            throw new RuntimeException("只能评价已完成的订单");
        }

        // 检查是否已经评价过
        Long existingReviews = count(new LambdaQueryWrapper<FoodReviews>()
                .eq(FoodReviews::getOrderId, foodReviews.getOrderId()));

        if (existingReviews > 0) {
            throw new RuntimeException("该订单已评价");
        }

        // 设置商家ID（从订单中获取）
        foodReviews.setBusinessId(order.getBusinessId());

        // 设置评价时间
        foodReviews.setCreatedTime(new Date());

        // 保存评价
        save(foodReviews);

        // 更新商家评分信息
        updateBusinessRating(foodReviews.getBusinessId());

        // 更新订单评价状态
        orderService.update(new LambdaUpdateWrapper<Orders>()
                .eq(Orders::getOrderId, foodReviews.getOrderId())
                .set(Orders::getIsReviewed, true));
    }

    /**
     * 更新商家评分信息
     */
    private void updateBusinessRating(Integer businessId) {
        // 获取该商家的所有评价
        List<FoodReviews> allReviews = list(new LambdaQueryWrapper<FoodReviews>()
                .eq(FoodReviews::getBusinessId, businessId));

        if (!allReviews.isEmpty()) {
            // 计算平均分
            double averageRating = allReviews.stream()
                    .mapToDouble(FoodReviews::getRating)
                    .average()
                    .orElse(0.0);

            // 更新商家信息
            businessService.update(new LambdaUpdateWrapper<Business>()
                    .eq(Business::getBusinessId, businessId)
                    .set(Business::getAverageRating, averageRating)
                    .set(Business::getRatingCount, allReviews.size()));
        }
    }

}


